package com.example.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.login.ui.login.LoginActivity;
import com.example.room.user.User;
import com.example.room.user.UserDao;
import com.example.xc.R;
import com.example.room.DbManager;
import com.example.room.ZRoomDB;


/**
 * 注册页面/添加学生页面
 */
public class RegisterActivity extends AppCompatActivity {
    private EditText etPhone;
    private EditText etPwd;
    private EditText etClass;
    private EditText etName;
    private EditText etNumber;
    private Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        TextView tvTitle = findViewById(R.id.textView);
        ImageView tvBack = findViewById(R.id.back);
        etPhone = findViewById(R.id.et_user_name);
        etPwd = findViewById(R.id.et_user_pwd);
        etClass = findViewById(R.id.et_ban_ji);
        etName = findViewById(R.id.et_xin_ming);
        etNumber = findViewById(R.id.et_xue_hao);
        etNumber = findViewById(R.id.et_xue_hao);
        btnRegister = findViewById(R.id.btn_register);
        //标题显示
        int type = getIntent().getIntExtra("isRegister", 0);
        tvTitle.setText(type == 1 ? "添加学生" : "注册");
        btnRegister.setText(type == 1 ? "添加学生" : "注册");
        tvBack.setOnClickListener(v -> finish());
        // 注册
        btnRegister.setOnClickListener(v -> {
            if (register() == 1) {
                if(type==0){
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } else {
                Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 注册
     *
     * @return 1成功 0失败
     */
    int register() {
        int status = 0;
        try {
            ZRoomDB zRoomDB = DbManager.INSTANCE.getDB(this);
            UserDao userDao = zRoomDB.userDao();
            User lastUser = userDao.queryUserMax();
            int id = 1;
            if (lastUser != null) {
                id = lastUser.getId() + 1;
            }
            User user = new User(id, etPhone.getText().toString().trim(), etPwd.getText().toString().trim(),
                    etName.getText().toString().trim(), etClass.getText().toString().trim(), etNumber.getText().toString().trim());
            userDao.addUser(user);
            status = 1;
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
        return status;
    }
}